//
//  DmsWrapper.m
//  DLNADemo
//
//  Created by apple on 14-12-18.
//  Copyright (c) 2014年 skyworth.digital. All rights reserved.
//

#import "DmsWrapper.h"
//#import "Platinum.h"
//#import <Platinum/Platinum.h>
//#import "SK_MediaDmsDataBase.h"
#import <Platinum/SK_Platinum.h>
#import "MediaItem.h"
#import "TSLibraryImport.h"


#import <objc/runtime.h>
#import "NSString+ContainsString.h"
#define IMAGE_QUALITY_LOW 0.7
#define IMAGE_QUALITY_HIGH 1.0

static  char associatedkey;

typedef NS_ENUM(NSUInteger, ImageType) {
    IMAGE_FULLSCREEN,
    IMAGE_THUMBNAIL,
    IMAGE_ORIGIN,
};


typedef NS_ENUM(NSUInteger, RequestMediaType) {
    RequestMediaTypeImage,
    RequestMediaTypeImageIcon,
    RequestMediaTypeMusic,
    RequestMediaTypeMusicIcon,
    RequestMediaTypeAssetVideo,
    RequestMediaTypeAssetVideoIcon,
};

@implementation DmsWrapper{
//    GCDWebServer *webServer;
    NSString *dmsName;

}


+(DmsWrapper*)sharedDmsWrapper{
   
    static DmsWrapper *sharedDmsWrapper = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
        sharedDmsWrapper = [[[self class] alloc] init];
    });
    return sharedDmsWrapper;
}

+ (ALAssetsLibrary *)defaultAssetsLibrary{
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library;
}



-(instancetype)init{

    self = [super init];
    if (!self) {
        return nil;
    }
    [self installNotificationHandler];
    return self;
}

-(void)dealloc{
    
    [self uninstallNotificationHandler];
}

-(void)start{
    [self initServer];
//    [self startHttpServer];
}

-(void)stop{
    
    PltDatabaseDMSStop();
}

-(void)installNotificationHandler{
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
}

-(void)uninstallNotificationHandler{

    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}


-(NSString*)getIpAddress{
//    return [webServer getIpAddress];
    return @"";
}

-(NSString*)getDmsName{
    return dmsName;
}


-(void)initServer{
    NSString *deviceName = [[UIDevice currentDevice] name];
    dmsName = [NSString stringWithFormat:@"多屏互动(%@)",deviceName];
    NSString *uuid = [[NSUserDefaults standardUserDefaults] valueForKey:@"uuid"];
    if (uuid ==nil) {
        CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
        uuid = (NSString *)CFBridgingRelease(CFUUIDCreateString (kCFAllocatorDefault,uuidRef));
        [[NSUserDefaults standardUserDefaults] setValue:uuid forKey:@"uuid"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    NSLog(@"device--uuid = %@",uuid);
    uuid = [uuid substringFromIndex:uuid.length-12]; //取后12位
  int result =  PltDatabaseDMSSetup([dmsName cStringUsingEncoding:NSUTF8StringEncoding], 10243, [uuid cStringUsingEncoding:NSUTF8StringEncoding]);
    NSLog(@"setup--%d",result);
}

#pragma mark DMS  Callbacks


/**
 *  数据源回调接口----
 *
 *  @param requestMedia
 *  @param result
 *
 *  @return
 */

int mediaRequestResult(const MediaInfo& requestMedia,RequestResultMediaInfo& result){
    NSLog(@"func---%s",__FUNCTION__);
    
    NSLog(@"request type = %s  ,requestPath = %s",requestMedia.mediaName.GetChars(),requestMedia.id.GetChars());
    switch(requestMedia.flag){
        case MEDIA_REQUEST_FLAG_DEVICEICON:
            break;
        case MEDIA_REQUEST_FLAG_ICON://suo lue tu
        {
        
            result.mediaSourceType = MEDIA_SOURCE_TYPE_BYTEARRAY;
            result.mimeType = "image/png";
            NSString *path = [[NSString alloc] initWithCString:requestMedia.id.GetChars() encoding:NSUTF8StringEncoding];
            @synchronized(path){
                NSData *data  = [[DmsWrapper sharedDmsWrapper] dataForIconResourceWithRequestPath:path];
                
                result.dataBuffer = *new NPT_DataBuffer(data.bytes,(int)data.length,false);
                break;
            }
            
        }
        default:
            result.mediaSourceType = MEDIA_SOURCE_TYPE_FILEPATH;
            NSString *path = [[NSString alloc] initWithCString:requestMedia.id.GetChars() encoding:NSUTF8StringEncoding];
            NSString *translatedPath =[[DmsWrapper sharedDmsWrapper] translatePath:path];
            result.filePath = [translatedPath cStringUsingEncoding:NSUTF8StringEncoding];
            break;
    }
    return 0;
}

/**
 *  数据源回调接口-----处理 browse请求，返回文件（夹）个数
 *
 *  @param mediaType 多媒体类型
 *
 *  @return 文件（夹）个数
 */
int getFolderChildrenCountResult(int mediaType){
    NSLog(@"func---%s",__FUNCTION__);
    DmsWrapper *sharedDmsWrapper = [DmsWrapper sharedDmsWrapper];
    if ([sharedDmsWrapper.datasource respondsToSelector:@selector(folderChildrenCount:)]) {
        int num = [sharedDmsWrapper.datasource folderChildrenCount:MEDIA_PHOTOS];
        
        return num;
    }
    return 0;
    
}

/**
 *  数据源回调接口----处理 browse请求,以路径形式返回文件。（在此项目中只支持search形式的，固这里不作处理）
 *  @param browseArgs 请求的一些参数
 *  @param result     存放结果用
 *
 *  @return 成功返回0
 */
int handleBrowseDms(const BrowseArgs& browseArgs,BrowseOrSearchResult& result){
    NSLog(@"func---%s",__FUNCTION__);
    MediaType mediaType;
    switch (browseArgs.mediaType) {
        case 0:
            mediaType = MEDIA_AUDIO;
            break;
        case 1:
            mediaType = MEDIA_PHOTOS;
            break;
        case 2:
            mediaType = MEDIA_VIDEO;
            break;
        case 3:
            mediaType = MEDIA_DIRECTTV;
            break;
        case 4:
            mediaType = MEDIA_PVRREC;
            break;
        case 5:
            mediaType = MEDIA_EPG;
            break;
        default: mediaType = MEDIA_VIDEO;
            break;
    }
    int startIndex = browseArgs.starting_index;
    DmsWrapper *sharedDmsWrapper = [DmsWrapper sharedDmsWrapper];
    NSArray *array =   [sharedDmsWrapper.datasource mediaInfoWithType:mediaType Index:startIndex Count:browseArgs.requested_count];
    for (int i = 0; i< array.count; i++) {
        MediaItem *item = [array objectAtIndex:i];
        MediaInfo_ info;
        info.mediatype = item.mediaType;
        info.mediaName = [item.name cStringUsingEncoding:NSUTF8StringEncoding];
        info.filePath = [item.url cStringUsingEncoding:NSUTF8StringEncoding];
        info.title = [item.name cStringUsingEncoding:NSUTF8StringEncoding];
        info.hasicon = 0;
        info.id = [item.url cStringUsingEncoding:NSUTF8StringEncoding];
        info.duration = item.duration?[item.duration intValue]:0;
        info.artist = [item.artist cStringUsingEncoding:NSUTF8StringEncoding];
        info.objectClass = [item.objectClass cStringUsingEncoding:NSUTF8StringEncoding];
        
        result.mediaList.Add(info);
    }
    result.totalMatches = (int)array.count;
    return 0;
}
/**
 *  数据源回调接口----处理search请求，以数据集的形式返回请求结果
 *
 *  @param searchArgs 请求的一些参数
 *  @param result     用于储存结果
 *
 *  @return 返回0表示成功
 */
int handleSearchDms(const SearchArgs& searchArgs,BrowseOrSearchResult& result){
    
    NSLog(@"func---%s",__FUNCTION__);
    
    NSString *searchCriteria = [[NSString alloc] initWithCString: searchArgs.search_criteria encoding:NSUTF8StringEncoding];
    NSArray *strs = [searchCriteria componentsSeparatedByString:@"\"" ];
    NSString *requestType;
   
    if (strs.count>=3) {
        requestType = [strs objectAtIndex:1];
    }
    
    MediaType mediaType;
    if ([requestType isEqualToString:OBJECT_CLASS_VIDEO_TYPE1]) {
        mediaType = MEDIA_VIDEO;
        
    }else if ([requestType isEqualToString:OBJECT_CLASS_AUDIO_TYPE1]){
        mediaType = MEDIA_AUDIO;
    
    }else if ([requestType isEqualToString:OBJECT_CLASS_IMAGE_TYPE1]){
        mediaType = MEDIA_PHOTOS;
    
    }
    int startIndex = searchArgs.starting_index;
    DmsWrapper *sharedDmsWrapper = [DmsWrapper sharedDmsWrapper];
    NSArray *array =   [sharedDmsWrapper.datasource mediaInfoWithType:mediaType Index:startIndex Count:searchArgs.requested_count];
    
    for (int i = 0; i< array.count; i++) {
        
        MediaItem *item = [array objectAtIndex:i];
        MediaInfo_ info;
        info.mediatype = item.mediaType;
        info.mediaName = [item.name cStringUsingEncoding:NSUTF8StringEncoding];
        info.filePath = [item.url cStringUsingEncoding:NSUTF8StringEncoding];
        info.title = [item.name cStringUsingEncoding:NSUTF8StringEncoding];
        info.hasicon = 0;
        info.id = [item.url cStringUsingEncoding:NSUTF8StringEncoding];
        info.duration = item.duration?[item.duration intValue]:0;
        info.artist = [item.artist cStringUsingEncoding:NSUTF8StringEncoding];
        info.objectClass = [item.objectClass cStringUsingEncoding:NSUTF8StringEncoding];
        result.mediaList.Add(info);
        
    }
    
    result.totalMatches = (int)array.count;

    return 0;
    
}

NPT_Result onBookOrRecordEventCallApp(
                                      PLT_ActionReference&			action,
                                      const BookOrRecordEventInfo& 	bookOrRecordEvent,
                                      ActionMessage& 					result){

    return NPT_SUCCESS;
}




NPT_Result onControlPointSearch(NPT_IpAddress& ipaddr,NPT_String user_agent, bool & isClientAllowed){


    return NPT_SUCCESS;
}



/**
 *  库中的回调接口（必需实现）  ，主要是对dms的action进行通知，暂时不需要用到
 *
 *  @param actionName         操作名
 *
 *  @param value              储存了对应操作的键值
 */
void dmsActionCallIOS(NPT_String& actionName,NPT_Map<NPT_String, NPT_String>& value){
    NSLog(@"func---%s",__FUNCTION__);
    
}
/**
 *  库中的回调接口（必需实现）  ，主要是对dms的action进行通知，暂时不需要用到
 *
 *  @param actionName         操作名
 *
 *  @param value              储存了对应操作的键值
 */
void dmsActionCallIOSWITHOUT(NPT_String& actionName,NPT_Map<NPT_String, NPT_String>& value){
    
    NSLog(@"func---%s",__FUNCTION__);
    
}

#pragma mark notification

- (void)didEnterBackground:(NSNotification*)notification {

    [self stop];
}

- (void)willEnterForeground:(NSNotification*)notification {
    
//    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)); // 1
//
//    dispatch_after(popTime, dispatch_get_main_queue(), ^{
//        
//        [self initServer];
//    });
//    
  
    [self start];
}

-(NSString*)translatePath:(NSString *)path{
   //PhotosIcon/assets-library://asset/asset.JPG%3Fid=1A7E8F78-D18E-4935-8807-DF737D8F29F8&ext=JPG/15-08-18%2016:18:23.jpg.
    
    NSRange range = [path rangeOfString:@"id="];
    if (range.length == 0) {
        return nil;
    }

   
    
    if ([path myContainsString:@"assets-library://"]) {  //相册图片
        
        
        NSRange assetRange = [path rangeOfString:@"assets-library://"];
        
        
        //    NSString *urlSubstring = [path substringFromIndex:range.location];
        
        NSRange extNameRange		= [path rangeOfString:@"&ext="];
        NSString *subStr  = [path substringFromIndex:extNameRange.location+ extNameRange.length];
        
        NSRange sepRange = [subStr rangeOfString:@"/"];
        
        NSString *extName = [subStr substringToIndex: sepRange.location];
        
        NSString *itemUrl = [path substringWithRange:NSMakeRange(assetRange.location, extNameRange.location - assetRange.location + extNameRange.length + extName.length)];
        NSLog(@"itemUrl = %@",itemUrl);

        
        
        if ([path hasSuffix:@".png"]) { //请求资源缩略图
            if ([path myContainsString:@"&ext=MOV"] || [path myContainsString:@"&ext=mov"]) { //视频资源
                
                return   [self assetItemPathFor:path URL:itemUrl type:RequestMediaTypeAssetVideoIcon];
                
            }else{
                return   [self assetItemPathFor:path URL:itemUrl type:RequestMediaTypeImageIcon];

            }
        }else{//请求资源内容
            if ([path myContainsString:@"&ext=MOV"]|| [path myContainsString:@"&ext=mov"]) {
                
                return   [self assetItemPathFor:path URL:itemUrl type:RequestMediaTypeAssetVideo];
            }else{
                
                return   [self assetItemPathFor:path URL:itemUrl type:RequestMediaTypeImage];
            }
            
        }
        
        
    }else if ([path myContainsString:@"ipod-library://"]){ //音乐库(包含视频)
        
        NSRange range = [path rangeOfString:@"id="];
        
        NSRange range1 = [[path substringFromIndex:range.location] rangeOfString:@"/"];
        
        NSString *assetUrlId = [[path substringFromIndex:range.location] substringToIndex:range1.location];
        
        MediaItem *resultItem =[self getMediaItemWithUrlIdFromIpodLib:assetUrlId];
        
        
        if (resultItem) {
            __block NSURL *pathUrl;
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            [self exportAssetAtURL:resultItem.ipodMusicUrl withTitle:resultItem.name CompleteBlock:^(NSURL *url) {
                pathUrl = url;
               dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
            
            return pathUrl.path;
        }
    }
    
    return nil;
}

-(NSData*)dataForIconResourceWithRequestPath:(NSString*)path{

    NSRange ipodRange = [path rangeOfString:@"ipod-library://"];
    
    if (ipodRange.length == 0) {
        return [NSData data];
    }
    NSRange idRange = [path rangeOfString:@"id="];
    NSString *tmpStr = [path substringFromIndex:idRange.location];
    
    NSString *idStr = [[tmpStr componentsSeparatedByString:@"/"] firstObject];
    
    MediaItem *item = [self getMediaItemWithUrlIdFromIpodLib:idStr];
    
    NSData *data = [self imageDataWithUrl:item];
    
    return data;

}


-(NSString*)assetItemPathFor:(NSString *)requestPath URL:(NSString*)url type:(RequestMediaType)type{

    NSRange nameRange		= [requestPath rangeOfString:@"?id="];
//    NSString *nameStringPart = [requestPath substringFromIndex:NSMaxRange(nameRange)];
    
    NSString *str = [requestPath substringFromIndex:nameRange.location + nameRange.length];
    
    NSRange idRange = [str rangeOfString:@"&"];
    
    NSString *idStr = [str substringToIndex:idRange.location];
    
    
    NSString *fileNamePrefix = @"D_P_RES_%@";
    NSString *suffix = [[requestPath componentsSeparatedByString:@"/"] lastObject];
    
    NSString *fileName = [NSString stringWithFormat:@"%@%@%@",fileNamePrefix, idStr,suffix];
    
    //NSString *tempDir = [self getDocumentPath];
    NSString *tempDir = NSTemporaryDirectory();
    NSString *filePath = [tempDir stringByAppendingPathComponent:fileName];
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        
        __block UIImage		 *imageToSend = nil;
        __block AVURLAsset *videoAsset = nil;
        
        __block BOOL hasErrorFlag		= NO;
        
        NSURL *theResourceURL = [NSURL URLWithString:url];
        
        ALAssetsLibrary *al =	[DmsWrapper defaultAssetsLibrary];
        
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
        [al assetForURL:theResourceURL resultBlock:^(ALAsset *asset) {
            NSString *theType =	[asset valueForProperty:ALAssetPropertyType];
            if ([theType isEqualToString:ALAssetTypeVideo]) {
                
                videoAsset = [AVURLAsset URLAssetWithURL:theResourceURL options:nil];
            }else {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                CGImageRef iref ;
                if (type  == RequestMediaTypeImage) {
                   iref = [rep fullScreenImage];
                }else{
                    iref = [asset thumbnail];
                }
                if (iref) {
                    imageToSend = [UIImage imageWithCGImage:iref];
                }
            }
            hasErrorFlag = YES;
            dispatch_semaphore_signal(semaphore);
        } failureBlock:^(NSError *error) {
            NSLog(@"booya, cant get image - %@",[error localizedDescription]);
            hasErrorFlag = NO;
            dispatch_semaphore_signal(semaphore);
        }];
        dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
        
        if (!hasErrorFlag) {
            
            return nil;
        }
        
        if (!imageToSend && !videoAsset) {
            return nil;
        }
        
        if (imageToSend) {
            BOOL flag = [UIImageJPEGRepresentation(imageToSend, 1.0) writeToFile:filePath atomically:YES];
            imageToSend = nil;
            if (!flag) {
                return nil;
            }
        }else if(videoAsset) {
            
            AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]
                                                   initWithAsset:videoAsset
                                                   presetName:AVAssetExportPresetLowQuality];
            exportSession.outputURL = [NSURL fileURLWithPath:filePath];
            exportSession.outputFileType = AVFileTypeQuickTimeMovie;
            
            __block BOOL retResult = NO;
            
            dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
            
            [exportSession exportAsynchronouslyWithCompletionHandler:^{
                
                if (exportSession.status == AVAssetExportSessionStatusCompleted) {
                    NSLog(@"export session completed");
                    retResult = YES;
                } else {
                    NSLog(@"export session error");
                }
                
                dispatch_semaphore_signal(semaphore);
            }];
            dispatch_semaphore_wait(semaphore,DISPATCH_TIME_FOREVER);
            videoAsset = nil;
        }
    }

    return filePath;
}

#pragma mark httpServer
/*
-(void)startHttpServer{
    webServer = [[GCDWebServer alloc] init];
    
    __weak DmsWrapper *sharedDms = self;
    
    [webServer addDefaultHandlerForMethod:@"GET"
                             requestClass:[GCDWebServerRequest class]
                        asyncProcessBlock:^(GCDWebServerRequest* request, GCDWebServerCompletionBlock completionBlock) {
                            
                            
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(100 * NSEC_PER_MSEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                                
                                NSLog(@"requestType--%@",request.contentType);
                                
                                
                                
                                [sharedDms dataWithName:request.URL.absoluteString Request:request CompleteBlock:^(GCDWebServerResponse *response) {
                                    completionBlock(response);
                                }];
                              
                               // GCDWebServerResponse *response = [sharedDms videoDataForUrl:request.URL.absoluteString Request:request];
                                
                               // completionBlock(response);
                                
                            });
                            
                        }];
    

    
    [webServer startWithPort:10240 bonjourName:@""];
}*/

#pragma mark GCDWebServerDataSource
/**
 *  根据请求来查找资源并读取资源然后response
 *
 *  @param name          请求的url
 *  @param request
 *  @param completeBlock  完成后的回调
 *//*
-(void)dataWithName:(NSString *)name Request:(GCDWebServerRequest*)request CompleteBlock:(void(^)(GCDWebServerResponse *response))completeBlock{
    
    NSLog(@"request---name--%@",name);
    
    
    
    __block  GCDWebServerResponse *response;
    
    if ([name myContainsString:@"assets-library://"]) {  //相册图片
        NSRange range = [name rangeOfString:@"id="];
        if (range.length == 0) {
            response = [[GCDWebServerDataResponse alloc] initWithData:[NSData data] contentType:@"image/png"];
        }
        
        NSRange range1 = [name rangeOfString:@"&"];
        if (range1.length == 0) {
            response = [[GCDWebServerDataResponse alloc] initWithData:[NSData data] contentType:@"image/png"];
        }
        NSString *assetUrl = [name substringWithRange:NSMakeRange(range.location, range1.location - range.location)];
      
        NSString *assetUrlId = [name substringWithRange:NSMakeRange(range.location, range1.location-range.location)];
        MediaItem *resultItem =[self getMediaItemWithUrlIdFromIpodLib:assetUrlId];
       // NSData *data = [self responseDataForAssetUrl:assetUrl];
        
        if ([name hasSuffix:@".png"]) { //请求资源缩略图
            if ([name myContainsString:@"&ext=MOV"] || [name myContainsString:@"&ext=mov"]) { //视频资源
                [self getImage:resultItem.imageAssetUrl CompleteBlock:^(UIImage *image) {
                    NSData *data = UIImagePNGRepresentation(image);
                    response = [[GCDWebServerDataResponse alloc] initWithData:data contentType:@"image/png"];
                    completeBlock(response);
                }];
            }else{
                [self responseDataForAssetUrl:assetUrl ImageType:IMAGE_THUMBNAIL CompleteBlock:^(NSData *data) {
                    
                    response = [[GCDWebServerDataResponse alloc] initWithData:data contentType:@"image/png"];
                    completeBlock(response);
                    
                }];
            }
        }else{//请求资源内容
            if ([name myContainsString:@"&ext=MOV"]|| [name myContainsString:@"&ext=mov"]) {
                [self exportAssetAtURL:resultItem.imageAssetUrl withTitle:resultItem.name CompleteBlock:^(NSURL *url) {
                    GCDWebServerResponse* response = [GCDWebServerFileResponse responseWithFile:url.path byteRange:request.byteRange];
                    [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];
                    completeBlock(response);
                }];
            }else{
            
                [self responseDataForAssetUrl:assetUrl ImageType:IMAGE_FULLSCREEN CompleteBlock:^(NSData *data) {
                    response = [[GCDWebServerDataResponse alloc] initWithData:data contentType:@"image/png"];
                    completeBlock(response);
                }];
            }
            
        }
        
        
    }else if ([name myContainsString:@"ipod-library://"]){ //音乐库(包含视频)
        
        
        
        //response = [[GCDWebServerDataResponse alloc] initWithData:[NSData data] contentType:@"audio/mpeg"];
        
        NSRange range = [name rangeOfString:@"id="];
        if (range.length == 0) {
            response = [[GCDWebServerDataResponse alloc] initWithData:[NSData data] contentType:@"audio/mpeg"];
            completeBlock(response);
            return;
        }
        
        NSRange range1 = [[name substringFromIndex:range.location] rangeOfString:@"/"];
        if (range1.length == 0) {
            response = [[GCDWebServerDataResponse alloc] initWithData:[NSData data] contentType:@"audio/mpeg"];
            completeBlock(response);
            return;
        }
        NSString *assetUrlId = [[name substringFromIndex:range.location] substringToIndex:range1.location];
        
        MediaItem *resultItem =[self getMediaItemWithUrlIdFromIpodLib:assetUrlId];
        
        if ([name hasSuffix:@".png"]) {  //请求资源封面图片。。。。。。
            
            NSData *thumbnailData =  [self imageDataWithUrl:resultItem];
            response = [[GCDWebServerDataResponse alloc] initWithData:thumbnailData contentType:@"image/jpg"];
            completeBlock(response);
            return;
        }

        if (resultItem) {
            [self exportAssetAtURL:resultItem.ipodMusicUrl withTitle:resultItem.name CompleteBlock:^(NSURL *url) {
              //  NSData *data = [NSData dataWithContentsOfURL:url];
               // response = [[GCDWebServerDataResponse alloc] initWithData:data contentType:@"audio/mpeg"];
                GCDWebServerResponse* response = [GCDWebServerFileResponse responseWithFile:url.path byteRange:request.byteRange];
                [response setValue:@"bytes" forAdditionalHeader:@"Accept-Ranges"];

                completeBlock(response);
            }];
            
        }

    }
}
*/
/**
 *  返回MediaItem的缩略图，这里主要是针对视频资源和音频资源
 *
 *  @param item 媒体对象
 *
 *  @return 图片数据
 */
-(NSData*)imageDataWithUrl:(MediaItem*)item{
    
    if (item.mediaType == MEDIA_VIDEO) {
        AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:item.ipodMusicUrl options:nil];
        AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
        generate1.appliesPreferredTrackTransform = YES;
        NSError *err = NULL;
        CMTime time = CMTimeMake(1, 2);
        CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
        UIImage *thumbnail = [[UIImage alloc] initWithCGImage:oneRef];
        
        if (thumbnail==nil) {
            return [NSData data];
        }
        return UIImageJPEGRepresentation(thumbnail, 1);
    }else if (item.mediaType == MEDIA_AUDIO){
        if (item.thumbnail) {
            return UIImageJPEGRepresentation(item.thumbnail, 1);
        }
    
    }

     return [NSData data];
    
}

/**
 *  根据资源的ID来查找资源，因为这里需要资源的assetUrl来读取对应的资源
 *
 *  @param urlId 资源的ID
 *
 *  @return 媒体对象
 */
-(MediaItem*)getMediaItemWithUrlIdFromIpodLib:(NSString*)urlId{
    
//    NSURL *ipodItemUrl;
    MediaItem *resultItem;
    
    NSMutableArray *tmpArray = [NSMutableArray new];
    [tmpArray addObjectsFromArray:self.musicsArray];
    [tmpArray addObjectsFromArray:self.videosArray];

    for (MediaItem *item in tmpArray) {
        NSRange range = [item.url rangeOfString:@"id="];
        if (range.length == 0) {
            continue;
        }
        
        NSString *assetId = [item.url substringFromIndex:range.location];
        if (assetId.length ==0) {
            continue;
        }
        
        NSRange range1 = [item.url rangeOfString:@"&ext="];
        if (range1.length>0) {
            assetId = [item.url substringWithRange:NSMakeRange(range.location, range1.location-range.location)];
        }
        
        if ([assetId isEqualToString:urlId]) {
            
            NSLog(@"found---------");
           // return item.ipodMusicUrl;
            resultItem = item;
        }
    }
    return resultItem;
}
/**
 *  这个方法主要响应对图片资源的请求，根据图片的assetUrl读取图片数据后response
 *
 *  @param assetUrl      资源的assetUrl
 *  @param imageType     图片类型，分为缩略图和原图
 *  @param completeBlock 完成后的回调
 */
-(void)responseDataForAssetUrl:(NSString*)assetUrl ImageType:(ImageType)imageType CompleteBlock:(void(^)(NSData *data))completeBlock{

    for (MediaItem *item in self.photosArray) {
        //   NSLog(@"asserurl---%@",[[asset valueForProperty:ALAssetPropertyAssetURL] absoluteString]);
        
        NSString *absUrl = item.url;
        NSRange range = [absUrl rangeOfString:@"id="];
        if (range.length == 0) {
            continue;
        }
        NSRange range1 = [absUrl rangeOfString:@"&"];
        if (range1.length == 0) {
            continue;
        }
        NSString *assetId = [absUrl substringWithRange:NSMakeRange(range.location, range1.location - range.location)];
        if ([assetId isEqualToString:assetUrl] && ![assetUrl isEqualToString:@""] && ![assetId isEqualToString:@""]) {
            ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
            [assetLibrary assetForURL:item.imageAssetUrl resultBlock:^(ALAsset *asset)
             {
                 ALAssetRepresentation *rep = [asset defaultRepresentation];
                 
            
                 
                 UIImage *image = [UIImage imageWithCGImage:rep.fullScreenImage];
                 NSData *data;
                 if (imageType == IMAGE_THUMBNAIL) {   //请求缩略图的时候 先缩小 再降低 质量。
//                    image = [self scaleImage:image toScale:0];
                    data = UIImageJPEGRepresentation(image, IMAGE_QUALITY_LOW);
                 }else{
                     data = UIImageJPEGRepresentation(image, IMAGE_QUALITY_HIGH);

                 }
           
                 
                 completeBlock(data);
             }
            failureBlock:^(NSError *err) {
                NSLog(@"Error: %@",[err localizedDescription]);
                completeBlock([NSData data]);
            }];
                      // return data;
            break;
        }
    }
}

- (UIImage *)scaleImage:(UIImage *)image toScale:(float)scaleSize

{
    
    int imageWidth = image.size.width<600? image.size.width:200;
    NSLog(@"imagewidth--%f",image.size.width);
    int imageHeight =  image.size.height*imageWidth/image.size.width;
    
    UIGraphicsBeginImageContext(CGSizeMake(imageWidth, imageHeight));
                                [image drawInRect:CGRectMake(0, 0, imageWidth, imageHeight)];
                                UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
                                UIGraphicsEndImageContext();
                                
                                return scaledImage;
}
/**
 *  这个方法用于将 音乐和视频资源导出到沙盒里
 *
 *  @param assetURL      资源的assetUrl
 *  @param title         资源的名称
 *  @param completeBlock 完成后的回调
 */
- (void)exportAssetAtURL:(NSURL*)assetURL withTitle:(NSString*)title CompleteBlock:(void(^)(NSURL* url))completeBlock{
    // create destination URL
    NSString* ext = [TSLibraryImport extensionForAssetURL:assetURL];
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *tmpDir = NSTemporaryDirectory();
    
    NSURL* outURL = [[NSURL fileURLWithPath:[tmpDir stringByAppendingPathComponent:title]] URLByAppendingPathExtension:ext];
    // we're responsible for making sure the destination url doesn't already exist
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outURL.path]) {
        NSLog(@"file exist");
        completeBlock(outURL);
        return;
    }
    [[NSFileManager defaultManager] removeItemAtURL:outURL error:nil];
    
    // create the import object
    TSLibraryImport* import = [[TSLibraryImport alloc] init];
    [import importAsset:assetURL toURL:outURL completionBlock:^(TSLibraryImport* import) {
        
//         * If the export was successful (check the status and error properties of
//         * the TSLibraryImport instance) you know have a local copy of the file
//         * at `outURL` You can get PCM samples for processing by opening it with
//         * ExtAudioFile. Yay!
//         *
//         *
        
        if (import.status != AVAssetExportSessionStatusCompleted) {
            // something went wrong with the import
            NSLog(@"Error importing: %@", import.error);
            import = nil;
            return;
        }
       
        import.isfinish = YES;
        completeBlock(outURL);
    }];
    //当导出文件较大时，所需时间较长，起个timer来更新进度
    [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(updateTranslationProgress:) userInfo:import repeats:YES];
    [[NSRunLoop currentRunLoop] run];
    
    
}

-(void)cancelExport{
    NSTimer *timer =  objc_getAssociatedObject(self, &associatedkey);
    if ([timer isKindOfClass:[NSTimer class]] == NO || !timer) {
        return;
    }
    TSLibraryImport *import = timer.userInfo;
    [import cancelExport];
    [timer invalidate];
}
-(void)updateTranslationProgress:(NSTimer*)timer{
    
    objc_setAssociatedObject(self, &associatedkey, timer, OBJC_ASSOCIATION_ASSIGN);
    
    TSLibraryImport *import = timer.userInfo;
    if (import.isfinish) {
        self.translationProgress = 1.0f;
        objc_setAssociatedObject(self, &associatedkey, nil, OBJC_ASSOCIATION_ASSIGN);
        [timer invalidate];
        return;
    }
    self.translationProgress = [import progress];

    NSLog(@"profg---%f",[import progress]);
};
/**
 *  检查沙盒中是否已经存在对应的资源，如果已经存在了就不需要再次导出了。。。
 *
 *  @param fileName 文件名
 *  @param url      资源的assetUrl
 *
 *  @return
 */
-(BOOL)checkFileIsExistWithFileName:(NSString *)fileName itemUrl:(NSString *)url{
    NSString *ext;
    if ([url myContainsString:@"assets-library://"]) {
        NSRange range = [url rangeOfString:@"id="];
        if (range.length == 0) {
            return NO;
        }
        
        NSRange range1 = [url rangeOfString:@"&"];
        if (range1.length == 0) {
            return NO;
        }
        NSString *assetUrlId = [url substringWithRange:NSMakeRange(range.location, range1.location-range.location)];
        MediaItem *resultItem =[self getMediaItemWithUrlIdFromIpodLib:assetUrlId];
        ext = [TSLibraryImport extensionForAssetURL:resultItem.imageAssetUrl];

    }else if ([url myContainsString:@"ipod-library://"]){
    
        NSRange range = [url rangeOfString:@"id="];
        if (range.length == 0) {
            
            return NO;
        }
        
        NSRange range1 = [[url substringFromIndex:range.location] rangeOfString:@"/"];
        if (range1.length == 0) {
            
            return NO;
        }
        NSString *assetUrlId = [[url substringFromIndex:range.location] substringToIndex:range1.location];
        
        MediaItem *resultItem =[self getMediaItemWithUrlIdFromIpodLib:assetUrlId];
        ext = [TSLibraryImport extensionForAssetURL:resultItem.ipodMusicUrl];
    }
    if (!ext) {
        return NO;
    }
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *tmpDir = NSTemporaryDirectory();
    NSURL* outURL = [[NSURL fileURLWithPath:[tmpDir stringByAppendingPathComponent:fileName]] URLByAppendingPathExtension:ext];
    // we're responsible for making sure the destination url doesn't already exist
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:outURL.path]) {
        NSLog(@"file exist");
        return YES;
    }
    return NO;
    
}
/**
 *  获取视频资源的缩略图
 *
 *  @param videoURL 视频的assetUrl
 *  @param block
 */
-(void)getImage:(NSURL *)videoURL CompleteBlock:(void(^)(UIImage * image))block

{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
        
        AVAssetImageGenerator *gen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
        
        gen.appliesPreferredTrackTransform = YES;
        
        CMTime time = CMTimeMakeWithSeconds(0.0, 600);
        
        NSError *error = nil;
        
        CMTime actualTime;
        
        CGImageRef image = [gen copyCGImageAtTime:time actualTime:&actualTime error:&error];
        UIImage *thumb = [[UIImage alloc] initWithCGImage:image];
        CGImageRelease(image);
        
        block(thumb);
    });
    
}




@end
